package com.gable.exhibition.controller;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.CacheData;
import com.gable.common.util.ReturnResultUtil;
import com.gable.common.util.StringUtil;
import com.gable.common.util.ZipUtil;
import com.gable.exhibition.model.User;
import com.gable.exhibition.service.NewsService;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.FileView;
import com.gable.exhibition.view.NewsView;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Lesson on 2018/3/9.
 */
@Controller
@RequestMapping(value="/news")
public class NewsController {

        Logger logger = Logger.getLogger(this.getClass());

        @Autowired
        NewsService newsService;

        @RequestMapping(value="/page")
        public String page(HttpServletRequest request, HttpServletResponse response){
            return "news/news-page";
        }

    @RequestMapping(value="/info")
    public String info(HttpServletRequest request, HttpServletResponse response){
            String newsId = request.getParameter("newsId");
            request.setAttribute("newsId",newsId);
        return "news/news-info";
    }

        @RequestMapping(value="/queryNewsList",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil queryNewsList(HttpServletRequest request, HttpServletResponse response, NewsView newsView){
            try{
                ReturnResultUtil rru = newsService.queryNewsList(newsView);
                logger.debug(JSON.toJSONString(rru));
                return rru;
            }catch (Exception e){
                e.printStackTrace();
            }
            return  new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
        }

        @RequestMapping(value="/saveNews",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil saveNews(HttpServletRequest request, HttpServletResponse response, NewsView newsView){
                try {
                    ReturnResultUtil rru = queryFileZipByNews(request);
                    if(rru.getRet() == 500)
                        return  rru;
                    String url = rru.getData() == null ? "": rru.getData().toString();
                    newsView.setUrl(url);

                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    User user = CacheData.getSessionUser(null,1);

                    if(newsView.getNewsId() == null){
                        newsView.setCreatePserson(user.getUserId());
                        newsView.setCreateTime(df.format(new Date()));
                    }else{
                        newsView.setUpdatePserson(user.getUserId());
                        newsView.setUpdateTime(df.format(new Date()));
                    }
                    if(newsView.getStatus().longValue() == 1){
                        newsView.setPublishPerson(user.getUserId());
                    }

                    if(newsView.getFileList()!= null){
                        List<FileView> list = JSON.parseArray(newsView.getFileList(),FileView.class);
                        newsView.setFileViewList(list);
                    }

                    return newsService.saveNews(newsView);
                }catch (Exception e){
                    e.printStackTrace();
                }
                return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
        }

        @RequestMapping(value="/queryNewsInfo",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil queryNewsInfo(HttpServletRequest request, HttpServletResponse response){
            try{
                if(StringUtil.isEmpty(request.getParameter("newsId"))){
                    new ReturnResultUtil(500,MessageUtil.NEWSIDISNULL);
                }
                Long newsId = Long.parseLong(request.getParameter("newsId"));
                ReturnResultUtil rru = newsService.queryNewsInfo(newsId);
                logger.debug(JSON.toJSONString(rru));
                return rru;
            }catch (Exception e){
                e.printStackTrace();
            }
            return new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
        }

        @RequestMapping(value="/withdraw",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil withdraw(HttpServletRequest request, HttpServletResponse response){
            try{
                if(StringUtil.isEmpty(request.getParameter("newsId"))){
                    new ReturnResultUtil(500,MessageUtil.NEWSIDISNULL);
                }
                Long newsId = Long.parseLong(request.getParameter("newsId"));
                ReturnResultUtil rru = newsService.withdraw(newsId);
                return rru;
            }catch (Exception e){
                e.printStackTrace();
            }
            return new ReturnResultUtil(500,MessageUtil.WITHDRAWEXCEPTION);
        }


    /**
     * 获取上传的压缩包文件
     * @param request
     * @return
     */
    public ReturnResultUtil queryFileZipByNews(HttpServletRequest request){
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("files");
            Long ym = new Date().getTime();
            //rootPath 将文件保存到磁盘路径
            ServletContext sc = request.getSession().getServletContext();
            String rootPath = sc.getRealPath("/")+"\\newsHtml\\";
            //filePath 访问项目上传的文件路径
            String filePath = "https://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
            filePath = filePath + "/newsHtml/"+ym + "/";
            File pathFile = new File(rootPath);
            if(!pathFile.exists()){
                pathFile.mkdirs();
            }
            String path = rootPath + ym;
            if (files != null && files.size() > 0) {
                for (MultipartFile m : files) {
                    if(m.getSize() == 0)
                        continue;
                    String suffix = m.getOriginalFilename().substring(m.getOriginalFilename().lastIndexOf(".") + 1);
                    if (!suffix.equals("zip")) {
                        return new ReturnResultUtil(500,MessageUtil.SUFFIXISNOTZIP);
                    }
                    File fileInfo = new File(path+"."+suffix);
                    m.transferTo(fileInfo);
                    filePath = filePath+ZipUtil.unZipFiles(fileInfo,path);
                    return new ReturnResultUtil(200,null,filePath);
                }
            }
            return new ReturnResultUtil(200,null);
        }catch (Exception e){
            e.printStackTrace();
        }
            return  new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
        }

        @RequestMapping(value="/publisNews",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil publisNews(HttpServletRequest request){
                try {
                    if(StringUtil.isEmpty(request.getParameter("id"))){
                        return new ReturnResultUtil(500,MessageUtil.NEWSIDISNULL);
                    }
                    Long newsId = Long.parseLong(request.getParameter("id"));
                    return  newsService.publisNews(newsId);
                }catch (Exception e){
                    e.printStackTrace();
                }
                return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
        }
}
